<template>
  <div class="profile">
    <header class="page-header">
      <h1>
        <i class="icon">👤</i>
        个人信息
      </h1>
      <p class="subtitle">管理您的个人资料和账户设置</p>
    </header>

    <div class="profile-content">
      <div class="profile-card">
        <div class="avatar-section">
          <div class="avatar">
            <i class="avatar-icon">👨‍💻</i>
          </div>
          <!-- <button class="btn-upload">
            <i class="icon">📷</i>
            更换头像
          </button> -->
        </div>

        <div class="info-section">
          <h2>基本信息</h2>
          
          <div class="info-grid">
            <div class="info-item">
              <label>
                <i class="icon">👤</i>
                用户名
              </label>
              <div class="info-value">
                <input 
                  v-model="userInfo.username" 
                  type="text" 
                  disabled
                  class="info-input"
                />
              </div>
            </div>

            <div class="info-item">
              <label>
                <i class="icon">✨</i>
                昵称
              </label>
              <div class="info-value">
                <input 
                  v-model="userInfo.nickname" 
                  type="text" 
                  :disabled="!isEditing"
                  class="info-input"
                />
              </div>
            </div>

            <div class="info-item">
              <label>
                <i class="icon">📧</i>
                邮箱
              </label>
              <div class="info-value">
                <input 
                  v-model="userInfo.email" 
                  type="email" 
                  :disabled="!isEditing"
                  class="info-input"
                />
              </div>
            </div>

            <div class="info-item">
              <label>
                <i class="icon">📞</i>
                手机号（支付宝号用于打款，谨慎填写）
              </label>
              <div class="info-value">
                <input 
                  v-model="userInfo.phone" 
                  type="tel" 
                  :disabled="!isEditing"
                  class="info-input"
                />
              </div>
            </div>

            <div class="info-item">
              <label>
                <i class="icon">📅</i>
                注册时间
              </label>
              <div class="info-value">
                <input 
                  v-model="userInfo.registerDate" 
                  type="text" 
                  disabled
                  class="info-input"
                />
              </div>
            </div>

           
           
  
          </div>

          <div class="action-buttons">
            <button 
              v-if="!isEditing" 
              class="btn btn-primary" 
              @click="isEditing = true"
            >
              <i class="icon">✏️</i>
              编辑资料
            </button>
            <template v-else>
              <button class="btn btn-success" @click="saveProfile">
                <i class="icon">✅</i>
                保存修改
              </button>
              <button class="btn btn-secondary" @click="cancelEdit">
                <i class="icon">❌</i>
                取消
              </button>
            </template>
          </div>

          <div class="logout-section">

          </div>
        </div>
      </div>

      <div class="stats-card">
        <h2>账户统计</h2>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-icon">📕</div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.articles }}</div>
              <div class="stat-label">发表文章</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">👁</div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.views }}</div>
              <div class="stat-label">总浏览量</div>
            </div>
          </div>
          <!-- <div class="stat-item">
            <div class="stat-icon">❤️</div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.likes }}</div>
              <div class="stat-label">获得点赞</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">�</div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.comments }}</div>
              <div class="stat-label">收到评论</div>
            </div>
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUserDetail, updateProfile, getUserStatistics } from '../api/user'
import toast from '../utils/toast'

const router = useRouter()
const isEditing = ref(false)
const loading = ref(false)

const userInfo = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  registerDate: '',
  bio: '',
  status: null
})

const userInfoBackup = {}

const userStats = reactive({
  articles: 0,
  views: 0,
  likes: 0,
  comments: 0
})

// 获取用户统计数据
const fetchUserStatistics = async () => {
  try {
    const response = await getUserStatistics()
    
    if (response.code === 200 && response.data) {
      const data = response.data
      // 更新统计数据
      userStats.articles = data.approvedArticleCount || 0
      userStats.views = data.totalViewCount || 0
      // 保留原有的点赞和评论数据
      // userStats.likes = 0
      // userStats.comments = 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 静默失败，不影响用户体验
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 从 localStorage 获取用户信息
    const userStr = localStorage.getItem('userInfo')
    if (!userStr) {
      toast.error('请先登录')
      router.push('/login')
      return
    }
    
    const user = JSON.parse(userStr)
    
    // 先用缓存数据填充界面，避免闪烁
    if (user.id) {
      Object.assign(userInfo, {
        id: user.id,
        username: user.username || '',
        nickname: user.nickname || '',
        email: user.email || '',
        phone: user.phone || '',
        status: user.status,
        registerDate: user.createTime || '',
        bio: user.bio || user.introduction || ''
      })
      
      // 备份数据
      Object.assign(userInfoBackup, userInfo)
    }
    
    const userId = user.id
    
    // 静默在后台获取最新数据
    loading.value = true
    const response = await getUserDetail(userId)
    
    if (response.code === 200 && response.data) {
      const data = response.data
      
      // 只在数据真正变化时才更新界面
      const newUserInfo = {
        id: data.id,
        username: data.username || '',
        nickname: data.nickname || '',
        email: data.email || '',
        phone: data.phone || '',
        status: data.status,
        registerDate: data.createTime || '',
        bio: data.bio || data.introduction || ''
      }
      
      // 检查数据是否变化
      if (JSON.stringify(newUserInfo) !== JSON.stringify(userInfo)) {
        Object.assign(userInfo, newUserInfo)
        Object.assign(userInfoBackup, userInfo)
        
        // 更新 localStorage 中的用户信息
        localStorage.setItem('userInfo', JSON.stringify(data))
      }
      
      // 更新统计信息（如果接口返回）
      if (data.stats) {
        Object.assign(userStats, {
          articles: data.stats.articles || 0,
          views: data.stats.views || 0,
          likes: data.stats.likes || 0,
          comments: data.stats.comments || 0
        })
      }
    }
    
    // 获取统计数据
    await fetchUserStatistics()
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 静默失败，不显示错误提示，因为已经有缓存数据
    if (!userInfo.id) {
      toast.error(error.message || '获取用户信息失败')
    }
  } finally {
    loading.value = false
  }
}

// 保存个人信息
const saveProfile = async () => {
  try {
    loading.value = true
    
    const response = await updateProfile({
      nickname: userInfo.nickname,
      email: userInfo.email,
      phone: userInfo.phone,
      bio: userInfo.bio
    })
    
    if (response.code === 200) {
      // 更新备份
      Object.assign(userInfoBackup, userInfo)
      
      // 更新 localStorage 中的用户信息
      const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
      user.nickname = userInfo.nickname
      user.email = userInfo.email
      localStorage.setItem('userInfo', JSON.stringify(user))
      
      isEditing.value = false
      toast.success('个人信息已保存')
    } else {
      toast.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    toast.error(error.message || '保存失败')
  } finally {
    loading.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  Object.assign(userInfo, userInfoBackup)
  isEditing.value = false
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('accessToken')
  localStorage.removeItem('refreshToken')
  localStorage.removeItem('userInfo')
  localStorage.removeItem('isLoggedIn')
  toast.success('已退出登录')
  router.push('/login')
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile {
  padding: 30px;
  background: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1rem;
  margin: 0;
}

.icon {
  font-style: normal;
}

.profile-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.profile-card,
.stats-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-section {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  margin-bottom: 30px;
}

.avatar {
  width: 120px;
  height: 120px;
  background: white;
  border-radius: 50%;
  margin: 0 auto 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.avatar-icon {
  font-size: 60px;
  font-style: normal;
}

.btn-upload {
  padding: 10px 24px;
  background: white;
  color: #667eea;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-upload:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.info-section h2 {
  margin: 0 0 25px 0;
  color: #2c3e50;
  font-size: 1.5rem;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-weight: 600;
  color: #555;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.info-input,
.info-textarea {
  padding: 10px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  font-family: inherit;
}

.info-input:disabled,
.info-textarea:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.info-input:not(:disabled):focus,
.info-textarea:not(:disabled):focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.info-textarea {
  resize: vertical;
  min-height: 100px;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.btn {
  flex: 1;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.btn-success {
  background: #27ae60;
  color: white;
}

.btn-success:hover {
  background: #229954;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(39, 174, 96, 0.3);
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(149, 165, 166, 0.3);
}

.stats-card h2 {
  margin: 0 0 25px 0;
  color: #2c3e50;
  font-size: 1.5rem;
}

.stats-grid {
  display: grid;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  font-size: 36px;
  font-style: normal;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

@media (max-width: 968px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
